<template>
  <div class="login">
    
    <!-- 项目名称 -->
    <div class="title">嗨购后台管理系统</div>

    <!-- 登陆表单 -->
    <!-- rules 定义表单项的校验规则 -->
    <el-form ref="ruleFormRef" class="login-form" :model="form" :rules="rules">
      <el-form-item prop="adminname">
        <el-input v-model="form.adminname"  placeholder="登陆用户:默认admin"/>
      </el-form-item>
     
      <el-form-item prop="password">
        <el-input v-model="form.password"  show-password placeholder="登陆密码:默认123456"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即登录</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script setup>

import { ref,reactive } from "vue";
import service from '@/api/index'

import { ElNotification } from 'element-plus'
import 'element-plus/es/components/notification/style/css'

import { useLoginStore } from '@/stores/login'
import { useRouter } from 'vue-router'

//实例化
var loginStore = useLoginStore()

//实例化路由管理对象
var $rotuer = useRouter()

//定义响应式数据
var form = ref({ adminname:'',password:'' })

var ruleFormRef = ref(null)

//定义表单的校验规则
const rules = reactive({
  adminname: [{ required: true, message: '请输入登陆账号', trigger: 'change' }],
  password: [{ required: true,message: '请输入密码', trigger: 'change'}],
})

//定义方法
var onSubmit = ()=>{
  //调用form组件实例的validate方法 对整个表单进行校验
  ruleFormRef.value.validate( async (valid, fields) => {
    if (valid) { //表单校验通过
      //发起登陆请求
      var res = await service.admin.admin_login( form.value )
      if( res.data.code == 200 ){
        //弹出通知
        ElNotification({
          title:'登陆通知',
          message:res.data.message,
          type:'success',
          duration: 1000
        })
        //保存登陆接口返回的信息( token,权限 )
        loginStore.saveLoginData(res.data.data);
        //跳转到主页
        $rotuer.push('/index');
        
      }else{
        ElNotification({
          title:'登陆通知',
          message:res.data.message,
          type:'error',
          duration: 1000
        })
      }
      
    } else { //表单校验未通过
      ElNotification({
        title:'校验通知',
        message: '表单校验失败!',
        type:'error',
        duration: 1000
      })
    }
  })
}

</script>

<style scoped>
.login{
  height: 100%;
  background: url(../../assets/bg.jpg) ;
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.login :deep(.el-button){
  width: 100%;
}
.login .title{
  font-size: 18px;
  text-align: center;
  margin-bottom: 20px;
}
.login .login-form{
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  min-width: 300px;
}
</style>